package exp6_1;

public class LinkedList {
    private Node head;

    public LinkedList() {
    }

    public LinkedList(Node head) {
        this.head = head;
    }

    public void add(Object data) {
        Node node = new Node(data);
        if (this.head == null) {
            this.head = node;
        } else {
            Node tmp = this.head;
            while (tmp.getNext() != null) {
                tmp = tmp.getNext();
            }
            tmp.setNext(node);
        }
    }

    public boolean remove(Object data) {
        if (this.head == null) {
            return false;
        }
        Node tmp = this.head;
        Node tmpr = this.head;
        while (tmp.getData() != data) {
            if (tmp.getNext() != null) {
                tmpr = tmp;
                tmp = tmp.getNext();
            } else {
                return false;
            }
        }
        if (tmp == this.head) {
            this.head = this.head.getNext();
        } else {
            tmpr.setNext(tmp.getNext());
        }
        return true;
    }

    public Node search(Object data) {
        if (this.head == null) {
            return null;
        }
        Node tmp = this.head;
        while (tmp.getData() != data) {
            if (tmp.getNext() != null) {
                tmp = tmp.getNext();

            } else {
                return null;
            }
        }
        return tmp;
    }

    public boolean insertAfter(Node previous, Object data) {
        if (previous == null || data == null) {
            return false;
        }
        if (previous.getNext() == null) {
            previous.setNext(new Node(data));
        } else {
            Node node = new Node(data);
            node.setNext(previous.getNext());
            previous.setNext(node);
        }
        return true;
    }

    public Node get(int index) {
        if (index < 0 || this.head == null) {
            return null;
        }
        Node tmp = this.head;
        for (int i = 0; i < index; i++) {
            if (tmp == null) {
                return null;
            }
            tmp = tmp.getNext();
        }
        return tmp;
    }

    public boolean set(Node node, Object data) {
        if (node == null || data == null) {
            return false;
        } else {
            node.setData(data);
            return true;
        }
    }

    public int size() {
        if (this.head == null) {
            return 0;
        }
        Node tmp = this.head;
        int i = 0;
        while (tmp != null) {
            tmp = tmp.getNext();
            i++;
        }
        return i;
    }


}
